package com.miao.im.support;

import com.miao.im.common.enums.LuaName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import reactor.core.publisher.Flux;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/4/23 21:45
 * @Description:
 */
@Component
public class RedisLuaExecutor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ReactiveStringRedisTemplate reactiveStringRedisTemplate;
    private static final Map<String, DefaultRedisScript<Long>> scriptMap = new HashMap<>();
    private final static String DIRECTORY_NAME = "lua";

    @PostConstruct
    public void init() throws FileNotFoundException {
        File luaFile = ResourceUtils.getFile("classpath:" + DIRECTORY_NAME);
        for (File file : luaFile.listFiles()) {
            String name = file.getName();
            DefaultRedisScript<Long> script = new DefaultRedisScript<>();
            script.setResultType(Long.class);
            script.setScriptSource(new ResourceScriptSource(new
                    ClassPathResource(DIRECTORY_NAME + "/" + name)));
            scriptMap.put(name, script);
        }
    }


    public void execute(LuaName luaName, List<String> keys, Object... args) {
        DefaultRedisScript<Long> script = scriptMap.get(luaName.getCode());
        if (script == null) {
            throw new RuntimeException("unknown redis lua script");
        }
        redisTemplate.execute(script, keys, args);
    }

    public Flux<Long> reactiveExecute(LuaName luaName, List<String> keys, Object... args){
        DefaultRedisScript<Long> script = scriptMap.get(luaName.getCode());
        if (script == null) {
            throw new RuntimeException("unknown redis lua script");
        }
        List<Object> list = new ArrayList<>(Arrays.asList(args));
        return reactiveStringRedisTemplate.execute(script, keys, list);
    }

}
